﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace y12fjydbs_1
{
    public partial class FrmComSelect : Form
    {
        Ini cIni;
        string strAppDir;

        public FrmComSelect()
        {
            InitializeComponent();

            strAppDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
            cIni = new Ini(strAppDir + "\\config.ini");

            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void FrmComSelect_Load(object sender, EventArgs e)
        {

            String[] Portname = SerialPort.GetPortNames();
            string selectCOM = cIni.ReadValue("COM", "Select","COM1");

            if(Portname.Length > 0)
            {
                foreach (var item in Portname)
                {
                    comboBox1.Items.Add(item);
                }
                if (Portname.Contains(selectCOM))
                {
                    comboBox1.SelectedItem = selectCOM;
                }
                else
                {
                    comboBox1.SelectedIndex = 0;
                }
            }
            else
            {
                MessageBox.Show("没有发现可用串口!");
            }
            

        }

        private void button1_Click(object sender, EventArgs e)
        { 
            try
            {
                SerialPort serialPort = new SerialPort( comboBox1.SelectedItem.ToString());
                serialPort.Open();

                if(serialPort.IsOpen)
                {
                    serialPort.Close();
                    MySerialPort.cComName = comboBox1.SelectedItem.ToString();
                    MySerialPort.cBand = 9600;
                }
                cIni.Write("COM", "Select", comboBox1.SelectedItem.ToString());
                
            }
            catch (Exception ee)
            {
                MessageBox.Show("端口打开失败,请重新选择端口!\n" + ee.Message);
                return;
            }

            //FrmYT frm = new FrmYT();
            FrmYDL frm = new FrmYDL();
            this.Hide();
            frm.Show();
        }
    }
}
